/*
## 随从状态管理

- 完善回合开始时的事件
  - 酒馆回合结束时, 保存场上卡牌的buff和属性(感觉可以复制一份player_soldiers, 回合开始时再整回来)
  - 战斗时, 记录可以永久保留的buff
  - 酒馆回合开始时, 恢复场面

 */

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class SoldierStateManager : MonoBehaviour
{
    [HideInInspector] public Dictionary<RoleTypeEnum, Dictionary<bool, List<GameObject>>> role_cards_dc => GameController.instance.role_cards_dc;
    
    public bool debug = false;

    [HideInInspector] public List<GameObject> player_soldiers => role_cards_dc[RoleTypeEnum.player][false];
    [HideInInspector] public List<GameObject> temp_player_soldiers => role_cards_dc[RoleTypeEnum.temp_player][false];
    
    public static SoldierStateManager instance;

    private void Awake()
    {
        if (instance != null)
            Destroy(this);
        instance = this;
    }

    public Transform temp_player_soldier_parent_trans;
    // public GameObject CloneGameObject(GameObject original)
    // {
    //     // 创建一个新的 GameObject，并复制原物体的 Transform（位置、旋转、缩放）
    //     GameObject newObject = new GameObject(original.name);
    //     // newObject.transform.position = original.transform.position;
    //     // newObject.transform.rotation = original.transform.rotation;
    //     // newObject.transform.localScale = original.transform.localScale;
    //     // newObject.transform.parent = original.transform.parent; // 如果需要复制父物体
    //     newObject.transform.parent = temp_player_soldier_parent_trans;
    //
    //     // 复制所有组件（除了 Transform）
    //     foreach (var component in original.GetComponents<Component>())
    //     {
    //         if (component is Transform) continue; // 忽略 Transform，因为已经复制
    //
    //         // 创建一个新组件并复制数据
    //         Component newComponent = newObject.AddComponent(component.GetType());
    //         CopyComponentData(component, newComponent);
    //     }
    //
    //     // 复制所有子物体
    //     foreach (Transform child in original.transform)
    //     {
    //         GameObject newChild = CloneGameObject(child.gameObject);
    //         newChild.transform.SetParent(newObject.transform); // 让新子物体成为新物体的子物体
    //     }
    //
    //     return newObject;
    // }
    
    public void CopyComponentData(Component original, Component copy)
    {
        // 获取原组件的所有字段，包括私有字段
        var fields = original.GetType().GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
    
        foreach (var field in fields)
        {
            // 获取字段的值，并将其赋给新的组件
            var value = field.GetValue(original);
            field.SetValue(copy, value);
        }
    }

    public enum CardCloneTypeEnum
    {
        origin,  // 原始卡牌
        attr,  // 仅克隆属性
        attr_and_buff_event,  // 属性 和 buff_event
    }

    public GameObject clone_one_card_with_buff_and_events(GameObject card_obj, CardCloneTypeEnum clone_type = CardCloneTypeEnum.attr_and_buff_event)
    {
        var card_comp = card_obj.GetComponent<CardController>();
        var buff_comp = card_obj.GetComponent<BuffHandle>();
        var new_card_obj = GameController.instance.core_load_card_obj_by_id(card_comp.card_data.id);
        
        new_card_obj.transform.position = GameController.instance._out_position;
        
        // CardController new_card_comp = new CardController();
        // var new_card_comp = (CardController)new_card_obj.AddComponent(card_comp.GetType());
        
        if (new_card_obj.GetComponent<CardController>() == null)
        {
            BdPackage.BdUtils.log("--- buff --- add CardController");
            new_card_obj.AddComponent<CardController>();
        }
        var new_card_comp = new_card_obj.GetComponent<CardController>();
        new_card_comp.parameter.copy_another_parameter(card_comp.parameter);;

        BdPackage.BdUtils.log($"--- card_name --- old_card_comp: {card_comp} -> new_card_comp: {new_card_comp}");

        new_card_comp.OnUse();

        if (clone_type == CardCloneTypeEnum.attr || clone_type == CardCloneTypeEnum.attr_and_buff_event)
            new_card_comp.set_current_atk_and_hp_value(card_comp.curr_atk, card_comp.curr_hp);

        // if (clone_type == CardCloneTypeEnum.attr_and_buff_event)
        // {
        //     // --- 接下来要把buff监听的event重新添加一遍
        //     if (new_card_obj.GetComponent<BuffHandle>() == null)
        //         new_card_obj.AddComponent<BuffHandle>();
        //     var new_buff_component = new_card_obj.GetComponent<BuffHandle>();
        //
        //     // foreach (var kvp in new_buff_component.event_ls_dc)
        //     // {
        //     //     foreach (var event_i in kvp.Value.Events)
        //     //     {
        //     //         if (!EventManager.instance.has_event(event_i))
        //     //             EventManager.instance.add_event(event_i);
        //     //     }
        //     // }
        //     // buff_comp.add_event_listener(event_i);
        // }
        return new_card_obj;
    }
    public void btn_save_current_soldiers_state()
    {
        List<GameObject> new_cards = new List<GameObject>();
        // 将player_soldiers的objects复制一份到temp_player_soldiers中去
        for (var i = 0; i < player_soldiers.Count; i++)
        {
            var soldier = player_soldiers[i];
            // 深度拷贝 GameObject
            // GameObject clonedSoldier = Instantiate(soldier, parent: temp_player_soldier_parent_trans);
            GameObject clonedSoldier = clone_one_card_with_buff_and_events(soldier);
            new_cards.Add(clonedSoldier);
            
            // 可选：自定义逻辑调整克隆对象（如命名或移除多余组件）
            clonedSoldier.name = soldier.name + "_Clone";
            
            // 添加到 temp_player_soldiers
            temp_player_soldiers.Add(clonedSoldier);
            
            var card_comp = clonedSoldier.GetComponent<CardController>();
            var buff_comp = clonedSoldier.GetComponent<BuffHandle>();
            BdPackage.BdUtils.assert(card_comp != null, "card_comp 不能为空!");
            BdPackage.BdUtils.assert(buff_comp != null, "buff_comp 不能为空!");
            BdPackage.BdUtils.assert(card_comp.parameter != null, "card_comp.parameter 不能为空!");
            BdPackage.BdUtils.assert(card_comp.card_data != null, "card_comp.card_data 不能为空!");
            BdPackage.BdUtils.log($"buffs.Count: {buff_comp.buffList.Count}" ,"--- card_name:", card_comp.card_data.card_name);

            if (card_comp.parameter != null)
            {
                card_comp.parameter.belong_to = RoleTypeEnum.temp_player;
            }
            card_comp.hide_obj();
        }
    }

    public void btn_restore_soldiers_state()
    {
        // 清空 player_soldiers 列表并销毁其所有对象
        foreach (var soldier in player_soldiers)
        {
            // Destroy(soldier); // 销毁旧的 GameObject
            GameController.instance.recycle_one_card(soldier);
        }
        player_soldiers.Clear();

        // 从 temp_player_soldiers 深度拷贝对象到 player_soldiers
        foreach (var tempSoldier in temp_player_soldiers)
        {
            var new_card_comp = tempSoldier.GetComponent<CardController>();
            new_card_comp.parameter.belong_to = RoleTypeEnum.player;
            new_card_comp.activate_event_callbacks();
            GameController.instance.move_card_to_selected_place(new_card_comp, ordering: 999);
        }

        // GameController.instance.refresh_place_cards_order(RoleTypeEnum.player, is_in_hand: false);

        // 清空 temp_player_soldiers 并销毁其所有对象
        // foreach (var tempSoldier in temp_player_soldiers)
        // {
        //     Destroy(tempSoldier); // 销毁临时对象
        // }
        
        temp_player_soldiers.Clear();
    }
    
    void Start()
    {

    }

    void Update()
    {
    }
}
